<template>
  <div>
    <a-modal v-model:visible="modalVisible" title="编辑上线时间" @ok="handleOk">
      <a-form layout="vertical">
        <a-form-item label="上线状态">
          <a-select v-model:value="orderStatusValue" placeholder="请选择上线状态">
            <a-select-option value="资料未提交">资料未提交</a-select-option>
            <a-select-option value="资料待审核">资料待审核</a-select-option>
            <a-select-option value="资料待复审">资料待复审</a-select-option>
            <a-select-option value="已反馈修改意见">已反馈修改意见</a-select-option>
            <a-select-option value="已上线">已上线</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="上线时间">
          <a-range-picker v-model:value="dateValue" show-time />
        </a-form-item>

        <a-form-item label="备注">
          <a-textarea v-model:value="notesValue" placeholder="请输入备注信息" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs, { Dayjs } from 'dayjs'
// @ts-ignore
import setOrderTimeService from '@/services/order/setOrderTime'

const [, setOrderTime] = setOrderTimeService()

const props = defineProps<{
  visible: boolean
  orderId: number
  value: [string, string] // 如 ["2025-06-01 10:00:00", "2025-06-02 18:00:00"]
  orderStatus?: string // 上线状态
  notes?: string // 备注
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}>()

const modalVisible = ref(props.visible)
const dateValue = ref<[Dayjs, Dayjs] | null>(null)
const orderStatusValue = ref<string>('')
const notesValue = ref<string>('')

watch(
  () => props,
  ({ visible, value, orderStatus: propOrderStatus, notes: propNotes }) => {
    modalVisible.value = visible

    const [start, end] = value || []
    if (start && end && dayjs(start).isValid() && dayjs(end).isValid()) {
      dateValue.value = [dayjs(start), dayjs(end)]
    } else {
      dateValue.value = null
    }

    orderStatusValue.value = propOrderStatus || ''
    notesValue.value = propNotes || ''
  },
  { immediate: true, deep: true }
)

watch(modalVisible, (val) => {
  emit('update:visible', val)
})

const handleOk = async () => {
  // 检查上线状态和时间范围是否至少有一个填写了
  if (!orderStatusValue.value && !dateValue.value) {
    message.warning('请至少填写上线状态或时间范围')
    return
  }

  let startTime = ''
  let endTime = ''

  if (dateValue.value) {
    const [start, end] = dateValue.value
    startTime = start.format('YYYY-MM-DD HH:mm:ss')
    endTime = end.format('YYYY-MM-DD HH:mm:ss')
  }

  const [err] = await setOrderTime({
    orderId: props.orderId,
    startTime,
    endTime,
    orderStatus: orderStatusValue.value,
    notes: notesValue.value
  })

  if (!err) {
    message.success('操作成功')
    emit('refresh')
    modalVisible.value = false
  } else {
    message.error(err.message)
  }
}
</script>
